import React, { Component } from "react";
import { StyleSheet, Dimensions, View, WebView } from "react-native";
// 获取设备的宽度和高度
const { height: deviceHeight } = Dimensions.get("window");

const BaseScript = `
(function () {
    var height = null;
    function changeHeight() {
      
        height = document.body.scrollHeight;
        height2 = document.documentElement.scrollHeight;
        height3 = document.body.clientHeight;
        if (window.postMessage) {
          window.postMessage(JSON.stringify({
            type: 'setHeight',
            height: height,
            height2: height2,
            height3: height3,
          }))
        }
    }

    document.addEventListener('message', function(msg) {
      setTimeout(changeHeight, 100);
    });
} ())
`;

export default class Index extends Component {
  state = {
    webViewHeight: deviceHeight,
  };

  onMessage = event => {
    try {
      const action = JSON.parse(event.nativeEvent.data);

      if (action.type === "setHeight") {
        if (
          action.height >= action.height2 &&
          action.height >= action.height3
        ) {
          this.setState({ webViewHeight: action.height });
        } else if (
          action.height2 >= action.height &&
          action.height2 >= action.height3
        ) {
          this.setState({ webViewHeight: action.height2 });
        } else if (
          action.height3 >= action.height &&
          action.height3 >= action.height2
        ) {
          this.setState({ webViewHeight: action.height3 });
        }
      }
    } catch (error) {
      // Toast.info(error);
    }
  };

  // 渲染
  render() {
    const { url = "" } = this.props;
    const { webViewHeight } = this.state;
    return (
      <View style={styles.container}>
        <WebView
          automaticallyAdjustContentInsets
          startInLoadingState
          scrollEnabled
          scalesPageToFit
          originWhitelist={["*"]}
          style={[styles.webView, { height: webViewHeight }]}
          onError={() => {}} // 加载失败的回调
          // onLoad={() => {
          //   this.webView.postMessage("loaded");
          // }} // 加载完成的回调
          onMessage={this.onMessage}
          onNavigationStateChange={() => {}} // 当导航状态发生改变的回调
          // <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          injectedJavaScript={`
                ${BaseScript} 
              `}
          source={{ uri: url }}
        />
      </View>
    );
  }
}
// 样式定义
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
});
